import {Component} from '@angular/core';
import {AlertController, IonicPage, ModalController, NavParams, ViewController} from 'ionic-angular';
import {StorageProvider} from "@providers/storage";
import {DialogProvider} from "@providers/dialog";
import {WorkerProvider} from "@providers/interface/worker";
import {Observable} from "rxjs/Observable";
import {Util} from "@providers/util";

/**
 * Generated class for the WorkerLookMaterielPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-worker-look-materiel',
  templateUrl: 'worker-look-materiel.html',
})
export class WorkerLookMaterielPage {

  categorys: any[] = [];//辅材分类
  allPros: any[] = [];//所有的辅材
  currentPros: any[] = [];//当前分类的辅材
  choosePros: any[] = [];//选中的辅材
  sum: number = 0;//选中辅材的总价
  num: number = 0;//选中辅材的个数
  userInfo: any = this.storage.read('userInfo');

  isClick: boolean = false;//Popover是否显示
  paramPros: any = this.navParams.get('materialCosts');//上级传过来的辅材
  product_id: any = this.navParams.get('product_id');//上级传过来的商品id
  SERVICETYPEID: any = this.navParams.get('SERVICETYPEID');//上级传过来的单据类型
  BJ: any = this.navParams.get('BJ');//上级传过来的单据类型
  safe: any = 0;

  updata() {
    this.sum = 0;
    this.num = 0;
    this.currentPros.forEach(value => {
      value.PRICE = +value.PRICE;
      if(Util.isNull(value.PRICE)||value.PRICE=='')value.PRICE=0;
    });
    this.choosePros.forEach(value => {
      if(Util.isNull(value.PRICE)||value.PRICE=='')value.PRICE=0;
      this.sum = +(this.sum + +(value.PRICE * value.QUANTITY).toFixed(2)).toFixed(2);
      this.num = +(this.num + +value.QUANTITY).toFixed(2);
    });
  }

  constructor(
    private storage: StorageProvider,
    private navParams: NavParams,
    private worker: WorkerProvider,
    private dialog: DialogProvider,
    private viewCtrl: ViewController,
    private modalCtrl: ModalController,
    private alertCrtl: AlertController,) {
  }

  ionViewDidLoad() {
    this.queryCategory().subscribe(message => {
      this.categorys = message.data;
      //初始化分类的选中辅材个数
      this.categorys.forEach(value => {
        value.num = 0;
        this.paramPros.forEach(val => {
          if (value.PRODUCT_CATEGORY_ID == val.PRODUCT_CATEGORY_ID) {
            value.num = +(+value.num + +val.QUANTITY).toFixed(2);
          }
        });
      });

      this.categorys.forEach((value, index) => {
        if (index == 0 || value.num > 0) {
          this.queryPro(value, index);
        } else {
          this.queryPro2(value, index);
        }
      });
    }, error => {
      this.dialog.showAlert("请检查网络");
    });
  }

  dismiss(data?: any) {
    if (data) {
      this.viewCtrl.dismiss(data);
    }else{
      this.viewCtrl.dismiss();
    }
  }

  /**
   * 确定按钮点击事件
   */
  onSubmit() {
    // if (this.num == 0) return;
    this.dismiss(this.choosePros);
  }

  /**
   * 清空选中的辅材
   */
  clearAll() {
    this.dialog.showConfirm(() => {
      this.choosePros.forEach(value => {
        value.QUANTITY = 0;
      });
      this.calculateChoose();
    }, "是否清空所有已选中的辅材！");
  }

  /**
   * 辅材数量改变点击事件
   * @param pro 选中的商品
   * @param index 为0时表示减小，为1时表示增加
   */
  quantityChange(pro: any, index?: number) {
    switch (index) {
      case 0:
        if (pro.QUANTITY == 0) return;
        pro.QUANTITY = +(pro.QUANTITY - 1).toFixed(2);
        if (pro.QUANTITY < 0) {
          pro.QUANTITY = 0;
        }
        break;
      case 1:
        /*if ((pro.QUANTITY + 1) > pro.PJSL) {
            this.dialog.showAlert("库存不足");
            return;
        }*/
        pro.QUANTITY = +(+pro.QUANTITY + 1).toFixed(2);
        break;
    }

    this.calculateChoose();
  }

  //失去焦点改变辅材数量
  eqc(pro: any) {
    this.editChange(pro);
  }

  //点击enter改变辅材数量
  kdqc(event, pro: any) {
    if (event.keyCode == 13) {
      this.editChange(pro);
    }
  }

  editChange(pro: any) {
    this.allPros.forEach(val => {
      val.forEach(value => {
        if (value.ZJ == pro.ZJ) {
          if (pro.currentQUANTITY == null) {
            pro.QUANTITY = 0;
            pro.currentQUANTITY = 0;
          } else {

            if (pro.currentQUANTITY > pro.PJSL) {
              // this.dialog.showAlert("库存不足");
              pro.currentQUANTITY = pro.QUANTITY;
              return;
            }
            pro.QUANTITY = +pro.currentQUANTITY.toFixed(2);
            if (pro.QUANTITY < 0) {
              pro.QUANTITY = 0;
              pro.currentQUANTITY = 0;
            }
          }
        }
      });
    });
    this.calculateChoose();
  }

  /**
   * 格式化选中的辅材，并计算个数和总费用
   */
  calculateChoose() {
    //获取所有的数量不为0的辅材
    let temp = [];
    this.allPros.forEach(value => {
      value.forEach(val => {
        temp.push(val);
      })
    });
    this.choosePros = temp.filter(value => {
      return value.QUANTITY > 0;

    });
    //计算数量不为0的辅材的个数和总价
    this.sum = 0;
    this.num = 0;
    this.choosePros.forEach(value => {
      this.sum = +(this.sum + +(value.PRICE * value.QUANTITY).toFixed(2)).toFixed(2);
      this.num = +(this.num + +value.QUANTITY).toFixed(2);
    });
    if (this.num == 0) {
      this.isClick = false;
    }
    //计算左侧的分类右上角的数字
    this.categorys.forEach(value => {
      value.num = 0;
      this.choosePros.forEach(val => {
        if (value.PRODUCT_CATEGORY_ID == val.PRODUCT_CATEGORY_ID) {
          value.num = +(+value.num + +val.QUANTITY).toFixed(2);
        }
      });
    });
  }

  /**
   * 根据分类查找出所有的辅材
   * @param category 分类
   * @param index 序号
   */
  queryPro(category: any, index: number) {

    if (this.allPros[index]) {
      this.categorys.forEach(value => {
        value["isSelected"] = false;
      });
      category.isSelected = true;

      this.currentPros = this.allPros[index];
      /*for(let i = 0; i<this.currentPros.length;i++){
        this.currentPros[i]['oldPic'] = this.currentPros[i].PRICE;
      }*/
      return;
    }

    this.worker.getFCFLSPFC({
      "FLID": category.PRODUCT_CATEGORY_ID,
      'SPID': this.product_id,
      "partyId": this.userInfo.PARTYID
    }).then(v => {
      this.allPros[index] = v.data;
      //初始化辅材数量
      console.info(this.allPros[index]);
      this.allPros[index].forEach(value => {
        value.QUANTITY = 0;
        value.currentQUANTITY = 0;
        this.paramPros.forEach(val => {
          // if (value.PRODUCT_ID == val.PRODUCT_ID)
          if (value.PRODUCT_ID == val.PRODUCT_ID) {
            value.QUANTITY = +val.QUANTITY;
            value.currentQUANTITY = val.QUANTITY;
            value.PRICE = +val.PRICE;
          }
        });
        console.info(value);
      });
      this.categorys.forEach(value => {
        value["isSelected"] = false;
      });
      category.isSelected = true;
      this.currentPros = this.allPros[index];
      /*for(let i = 0; i<this.currentPros.length;i++){
        this.currentPros[i]['oldPic'] = this.currentPros[i].PRICE;
      }*/
      this.calculateChoose();
    }).catch(e => {
      this.dialog.showAlert("请检查网络");
    });
  }

  /**
   * 查找出所有的辅材用辅材分类分组
   * @param category 分类
   * @param index 序号
   */
  queryPro2(category: any, index: number) {
    this.worker.getFCFLSPFC({
      "FLID": category.PRODUCT_CATEGORY_ID,
      'SPID': this.product_id,
      "partyId": this.userInfo.PARTYID
    }).then(v => {
      this.allPros[index] = v.data;
      //初始化辅材数量
      console.info(this.allPros[index]);
      this.allPros[index].forEach(value => {
        value.QUANTITY = 0;
        value.currentQUANTITY = 0;
        this.paramPros.forEach(val => {
          if (value.PRODUCT_ID == val.PRODUCT_ID) {
            value.QUANTITY = val.QUANTITY;
            value.currentQUANTITY = val.QUANTITY;
            value.PRICE = +val.PRICE;
          }
        });
        console.info(value);
      });
      this.calculateChoose();
    }).catch(e => {
      this.dialog.showAlert("请检查网络");
    });
  }

  /**
   * 查询辅材分类
   */
  queryCategory(level: number = 1, category_type: string = 'terrace'): Observable<any> {
    return Observable.create((observer) => {
      this.worker.getFCFL({'SPID': this.product_id, 'SERVICETYPEID': this.SERVICETYPEID,"partyId": this.userInfo.PARTYID}).then(v => {
        observer.next(v);
        observer.complete();
      }).catch(e => {
        observer.error(e);
      });
    });

  }

  /**
   * 创建modal
   * @param page
   * @param data
   */
  showQueryMaterialModal() {
    let modal = this.modalCtrl.create('MqueryMaterialPage',
      {
        'allPros': this.allPros,
        'categorys': this.categorys,
        'choosePros': this.choosePros
      });
    modal.onDidDismiss(data => {
      if (data) {
        this.calculateChoose();
      }
    });
    modal.present();
  }

  setPrice(item) {
    let alert = this.alertCrtl.create({
      message: "输入价格",
      inputs: [{type: 'number', name: 'price'}],
      buttons: [{
        text: "取消", handler: () => {
        }
      }, {
        text: "确定", handler: (res) => {
          if (item.XJ>res.price){//item.oldPic>res.price
            return this.dialog.showAlert("收费价格低于限价， 请调整价格。")
          }
          item.PRICE = res.price;
          this.updata();
        }
      }]
    });
    alert.present();
  }
}
